<template>
  <div class="card network-trend-card">
    <div class="card-header">
      <div class="title">
        <Icon icon="ant-design:wifi-outlined" :size="16" />
        <span>{{ t('tb.baseInfo.sections.network') }}</span>
      </div>
      <div class="vpn-status" v-if="vpn">
        <Icon icon="ant-design:cloud-server-outlined" />
        <span>VPN {{ vpn.label }}</span>
      </div>
    </div>
    <div v-if="data && data.length > 0" ref="chartRef" class="chart-container"></div>
    <div v-else class="empty-state">
      <Icon icon="ant-design:line-chart-outlined" :size="48" class="empty-icon" />
      <p class="empty-text">暂无网络趋势数据</p>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch, Ref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useECharts } from '/@/hooks/web/useECharts';
  import { Icon } from '/@/components/Icon';
  import type { NetworkHistoryItem, VpnMetric } from '../types';

  const props = defineProps<{
    data: NetworkHistoryItem[];
    vpn?: VpnMetric;
  }>();

  const { t } = useI18n();
  const chartRef = ref<HTMLDivElement | null>(null);
  const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

  watch(
    () => props.data,
    () => {
      updateChart();
    },
    { deep: true },
  );

  onMounted(() => {
    updateChart();
  });

  function formatMinuteLabel(value: string) {
    if (!value) return '';
    if (/^\d{2}:\d{2}$/.test(value)) return value;
    const date = new Date(value);
    if (!Number.isNaN(date.getTime())) {
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${hours}:${minutes}`;
    }
    return value;
  }

  function updateChart() {
    const timestamps = props.data.map((item) => formatMinuteLabel(item.timestamp));
    const uploads = props.data.map((item) => item.upload);
    const downloads = props.data.map((item) => item.download);

    setOptions({
      tooltip: {
        trigger: 'axis',
        formatter: (params: any[]) => {
          if (!params?.length) return '';
          const timeLabel = params[0]?.axisValueLabel || '';
          const rows = params
            .map((item) => {
              const colorDot = `<span style="display:inline-block;margin-right:8px;width:8px;height:8px;border-radius:50%;background:${item.color};"></span>`;
              const name = item.seriesName || '';
              const value = Number.isFinite(item.value) ? `${item.value} Kbps` : '--';
              return `<div>${colorDot}${name}<span style="margin-left:12px;font-weight:600;">${value}</span></div>`;
            })
            .join('');
          return `<div style="padding:4px 8px;"><div style="margin-bottom:4px;font-weight:600;">${timeLabel}</div>${rows}</div>`;
        },
      },
      grid: {
        left: '2%',
        right: '2%',
        bottom: '3%',
        top: '5%',
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: timestamps,
        name: '',
        nameLocation: 'end',
        nameGap: 18,
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: {
          show: true,
          color: '#94a3b8',
        },
      },
      yAxis: {
        type: 'value',
        name: t('tb.baseInfo.network.speedAxis'),
        nameLocation: 'middle',
        nameGap: 30,
        nameRotate: 90,
        nameTextStyle: {
          color: '#94a3b8',
          fontWeight: 600,
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: '#e2e8f0',
          },
        },
        axisLabel: {
          color: '#94a3b8',
          margin: 12,
          formatter: (value: number) => value,
        },
      },
      series: [
        {
          name: t('tb.baseInfo.network.upload'),
          type: 'line',
          smooth: true,
          showSymbol: false,
          data: uploads,
          itemStyle: { color: '#0ea5e9' }, // Cyan/Blue
          lineStyle: { width: 3 },
        },
        {
          name: t('tb.baseInfo.network.download'),
          type: 'line',
          smooth: true,
          showSymbol: false,
          data: downloads,
          itemStyle: { color: '#ef4444' }, // Red
          lineStyle: { width: 3 },
        },
      ],
    });
  }
</script>

<style scoped lang="less">
  .card {
    background: #fff;
    border-radius: 16px;
    padding: 16px;
    box-shadow: 0 6px 20px rgba(15, 23, 42, 0.08);
  }
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  .title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    color: #0f172a;
  }
  .vpn-status {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: #22c55e;
    font-weight: 500;
  }
  .chart-container {
    width: 100%;
    height: 180px;
  }
  .empty-state {
    width: 100%;
    height: 180px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #94a3b8;
  }
  .empty-icon {
    margin-bottom: 12px;
    opacity: 0.5;
  }
  .empty-text {
    font-size: 14px;
    margin: 0;
  }
</style>
